package com.atguigu.utils;

import com.github.wxpay.sdk.WXPayUtil;
import com.google.common.collect.Maps;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;

/**
 * JWT工具类
 *
 * @author zy
 */
@Slf4j
public class JwtUtils {
    /**
     * 过期时间
     */
    public static final Long EXPIRE = 1000 * 60 * 60 * 24L;
    /**
     * 签名校验码/盐
     */
    public static final String APP_SECRET = "ukc8BDbRigUDaY6pZFfWus2jZWLPHO";

    /**
     * 获取JWT token编码
     */
    public static String getJwtToken(String id, String nickname) {
        return Jwts.builder()
                //头信息
                .setHeaderParam("typ", "JWT")
                .setHeaderParam("alg", "HS256")
                .setIssuedAt(new Date())
                .setSubject("guli_token")
                //过期时间
                .claim("id", id)
                .claim("nickname", nickname)
                .setExpiration(new Date(System.currentTimeMillis() + EXPIRE))
                //添加签名校验码
                .signWith(SignatureAlgorithm.HS256, APP_SECRET)
                .compact();
    }

    /**
     * 判断token是否存在与有效
     *
     * @param jwtToken jwtToken
     * @return boolean boolean
     */
    public static boolean checkToken(String jwtToken) {
        //根据编码和token串进行校验
        if (StringUtils.isEmpty(jwtToken)) {
            return false;
        }
        try {
            Jwts.parser().setSigningKey(APP_SECRET).parseClaimsJws(jwtToken);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    /**
     * 判断token是否存在与有效
     *
     * @param request request
     * @return boolean boolean
     */
    public static boolean checkToken(HttpServletRequest request) {
        String token = request.getHeader("token");
        if (StringUtils.isEmpty(token)) {
            return false;
        }
        try {
            Jwts.parser().setSigningKey(APP_SECRET).parseClaimsJws(token);

        } catch (Exception e) {
            return false;
        }
        return true;
    }

    /**
     * 根据 token 获取会员ID
     *
     * @param request request
     * @return String
     */
    public static String getToken(HttpServletRequest request) {
        String token = request.getHeader("token");
        if (StringUtils.isEmpty(token)) {
            return null;
        }
        Jws<Claims> jws = Jwts.parser().setSigningKey(APP_SECRET).parseClaimsJws(token);
        Claims claims = jws.getBody();
        return (String) claims.get("id");
    }

    public static void main(String[] args) throws Exception {
        HashMap<String, String> map = Maps.newHashMap();
        map.put("ToUserName", "v1");
        System.out.println(WXPayUtil.mapToXml(map));
    }

}
